package com.tjcm.tjcminspectmanager;

import java.util.Arrays;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.dialog.DialogManager;
import cn.emagsoftware.ui.staticmanager.StaticManager;
import cn.emagsoftware.util.AsyncWeakTask;
import cn.emagsoftware.util.CodeException;
import cn.emagsoftware.util.DateUtilities;
import cn.emagsoftware.util.LogManager;

import com.tjcm.tjcminspectmanager.manager.NetManager;
import com.tjcm.tjcminspectmanager.model.User;
import com.tjcm.tjcminspectmanager.model.User.SpecialtyType;

public class PointCollectActivity extends BaseActivity
{
    private LocationManager  mgr      = null;
    private LocationListener listener = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (!LoginActivity.IS_APP_RUNNING)
        {
            StaticManager.restartAppWhenDalvikRecycled(this, LoginActivity.class);
            return;
        }

        final User user = (User) getIntent().getSerializableExtra("USER");

        setContentView(R.layout.pointcollect);

        final EditText time = (EditText) findViewById(R.id.time);
        final EditText lon = (EditText) findViewById(R.id.lon);
        final EditText lat = (EditText) findViewById(R.id.lat);
        final EditText name = (EditText) findViewById(R.id.name);
        final Spinner area = (Spinner) findViewById(R.id.area);
        final Spinner type = (Spinner) findViewById(R.id.type);
        final Spinner level = (Spinner) findViewById(R.id.level);
        Button submit = (Button) findViewById(R.id.submit);
        Button back = (Button) findViewById(R.id.back);

        time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
        lon.setText("0.00000");
        lat.setText("0.00000");
        mgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener = new LocationListener()
        {
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss"));
                lon.setText("0.00000");
                lat.setText("0.00000");
            }

            @Override
            public void onLocationChanged(Location location)
            {
                // TODO Auto-generated method stub
                time.setText(DateUtilities.getFormatDate(new Date(location.getTime()), "yyyy-MM-dd HH:mm:ss"));
                lon.setText(location.getLongitude() + "");
                lat.setText(location.getLatitude() + "");
            }
        };
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
        name.requestFocus();
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, User.AREA_NAME);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        area.setAdapter(areaAdapter);
        int index = Arrays.asList(User.AREA_NAME).indexOf(user.areaName);
        if (index != -1)
            area.setSelection(index);
        ArrayAdapter<SpecialtyType> typeAdapter = new ArrayAdapter<SpecialtyType>(this, android.R.layout.simple_spinner_item, User.SPECIALTY_TYPE);
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        type.setAdapter(typeAdapter);
        index = Arrays.asList(User.SPECIALTY_TYPE).indexOf(new SpecialtyType("", user.specialtyType));
        if (index != -1)
            type.setSelection(index);
        ArrayAdapter<String> levelAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, User.HIDDENTROUBLE_LEVEL);
        levelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        level.setAdapter(levelAdapter);
        submit.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                String nameStr = name.getText().toString();
                if (TextUtils.isEmpty(nameStr))
                {
                    ToastManager.showLong(PointCollectActivity.this, R.string.pointcollect_btn_submit_empty_name);
                    return;
                }
                String areaStr = (String) area.getSelectedItem();
                if (TextUtils.isEmpty(areaStr))
                {
                    ToastManager.showLong(PointCollectActivity.this, R.string.pointcollect_btn_submit_empty_area);
                    return;
                }
                String typeStr = ((SpecialtyType) type.getSelectedItem()).name;
                if (TextUtils.isEmpty(typeStr))
                {
                    ToastManager.showLong(PointCollectActivity.this, R.string.pointcollect_btn_submit_empty_type);
                    return;
                }
                String levelStr = (String) level.getSelectedItem();
                if (TextUtils.isEmpty(levelStr))
                {
                    ToastManager.showLong(PointCollectActivity.this, R.string.pointcollect_btn_submit_empty_level);
                    return;
                }
                String timeStr = time.getText().toString();
                String lonStr = lon.getText().toString();
                String latStr = lat.getText().toString();
                new AsyncWeakTask<String, Object, Object>(PointCollectActivity.this)
                {
                    protected void onPreExecute(Object[] objs)
                    {
                        ProgressDialog dialog = DialogManager.showProgressDialog((Context) objs[0], R.string.generic_dialog_title, R.string.pointcollect_btn_submit_process, null, null, true, false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
                        {
                            @Override
                            public void onCancel(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                cancel(true);
                            }
                        });
                        addToWeakReference(dialog);
                    }

                    protected Object doInBackgroundImpl(String... arg0) throws Exception
                    {
                        NetManager.pointCollectSubmit(arg0[0], arg0[1], arg0[2], arg0[3], arg0[4], arg0[5], arg0[6], arg0[7]);
                        return null;
                    }

                    protected void onPostExecute(Object[] objs, Object result)
                    {
                        ((ProgressDialog) objs[1]).dismiss();
                        final Activity activity = (Activity) objs[0];
                        DialogManager.showAlertDialog(activity, R.string.generic_dialog_title, R.string.pointcollect_btn_submit_success, new int[] { R.string.generic_dialog_btn_ok }, null, true,
                                false).setOnDismissListener(new DialogInterface.OnDismissListener()
                        {
                            @Override
                            public void onDismiss(DialogInterface dialog)
                            {
                                // TODO Auto-generated method stub
                                activity.finish();
                            }
                        });
                    }

                    protected void onException(Object[] objs, Exception e)
                    {
                        LogManager.logE(PointCollectActivity.class, "point collect failed.", e);
                        ((ProgressDialog) objs[1]).dismiss();
                        int resId;
                        if (e instanceof CodeException)
                        {
                            CodeException excep = (CodeException) e;
                            if (NetManager.CODE_IO.equals(excep.getCode()))
                                resId = R.string.generic_error_io;
                            else
                                resId = R.string.pointcollect_btn_submit_failed;
                        } else
                        {
                            resId = R.string.generic_error;
                        }
                        DialogManager.showAlertDialog((Context) objs[0], R.string.generic_dialog_title, resId, new int[] { R.string.generic_dialog_btn_ok }, null, true, false);
                    }
                }.execute(timeStr, nameStr, typeStr, lonStr, latStr, user.userId, areaStr, levelStr);
            }
        });
        back.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
        });
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (listener != null)
            mgr.removeUpdates(listener);
    }

}